<?php
namespace app\admin\controller;
use think\Db;
use think\Loader;
use app\admin\model\Link as Links;

class Link extends Base{

    //链接列表
    public function lst(){
        $links = Db::name('link') -> paginate(2);
        $this -> assign('links', $links);
        return $this -> fetch();
    }

    //新增链接
    public function add(){
        if(request() -> isPost()){
            $links = new Links();
            $links -> data([
                'title' => input('title'),
                'url' => input('url'),
                'desc' => input('desc'),
            ]);
            $validate = Loader::validate('Link');
            if($validate-> check($links)){
                if($links -> save()){
                    return $this -> success('添加链接成功！', 'link/lst');
                }else{
                    return $this -> error('添加链接失败！');
                }
            }else{
                return $this -> error($validate -> getError());
            }
            return;
        }

        return $this -> fetch();
    }

    public function add2(){
        if(request() -> isPost()){
            $data = [
                'title' => input('title'),
                'url' => input('url'),
                'desc' => input('desc'),
            ];
            $validate = Loader::validate('Link');
            if($validate-> check($data)){
                $db = Db::name('link') -> insert($data);
                if($db){
                    return $this -> success('添加链接成功！', 'link/lst');
                }else{
                    return $this -> error('添加链接失败！');
                }
            }else{
                return $this -> error($validate -> getError());
            }
            return;
        }

        return $this -> fetch();
    }

    //修改链接
    public function edit(){
        if(request() -> isPost()){
            $data = [
                'id' => input('id'),
                'title' => input('title'),
                'url' => input('url'),
                'desc' => input('desc'),
            ];
            $validate = Loader::validate('Link');
            if($validate-> check($data)){
                $db = Db::name('link') -> update($data);
                if($db){
                    return $this -> success('修改链接成功！', 'link/lst');
                }else{
                    return $this -> error('修改链接失败！');
                }
            }else{
                return $this -> error($validate -> getError());
            }
            return;
        }else{
            $id = input('id');
            $links = db('link') -> where('id', $id) -> find();
            $this -> assign('links', $links);
            return $this -> fetch();
        }


    }

    //删除链接
    public function del(){
        if(db('link')->delete(input('id'))){
            return $this -> success('删除链接成功！', 'link/lst');
        }else{
            return $this -> error('删除链接失败！');
        }
    }



}